package cn.kgc.dao.impl;

import cn.kgc.dao.BaseDao;
import cn.kgc.dao.NewsCategoryDao;
import cn.kgc.pojo.NewsCategory;
import com.sun.org.apache.xpath.internal.SourceTree;

import java.sql.ResultSet;
import java.sql.Timestamp;

public class NewsCategoryDaoImpl extends BaseDao implements NewsCategoryDao{

    //删除某个新闻类别
    public boolean deleteNewsCategory(NewsCategory newsCategory) {
        boolean flag = false;
        String sql = "delete from news_category where id=?";
        Object[] params = {newsCategory.getId()};
        if (this.getConnection()){
            try {
                int i = this.executeUpdate(sql, params);
                if (i>0){
                    System.out.println("删除新闻类别成功！");
                    flag = true;
                }else {
                    System.out.println("该类别不存在！");
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                this.closeResource();
            }
        }
        return flag;
    }

    public NewsCategory getNewsCategoryById(int id) {
        NewsCategory newsCategory = new NewsCategory();
        String sql = "select id,name,createDate from news_category where id=?";
        Object[] params = {id};
        if (this.getConnection()){
            try {
                ResultSet rs = this.executeQuery(sql, params);
                while (rs.next()){
                    int newId = rs.getInt("id");
                    String name = rs.getString("name");
                    Timestamp createdate = rs.getTimestamp("createdate");

                    newsCategory.setId(newId);
                    newsCategory.setName(name);
                    newsCategory.setCreateDate(createdate);
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                this.closeResource();
            }
        }
        return newsCategory;
    }

    public static void main(String[] args) {
        System.out.println(new NewsCategoryDaoImpl().getNewsCategoryById(0).getName());
        System.out.println(new NewsCategoryDaoImpl().getNewsCategoryById(1).getName());
        System.out.println(new NewsCategoryDaoImpl().getNewsCategoryById(2).getName());
        System.out.println(new NewsCategoryDaoImpl().getNewsCategoryById(3).getName());
        System.out.println(new NewsCategoryDaoImpl().getNewsCategoryById(4).getName());
        System.out.println(new NewsCategoryDaoImpl().getNewsCategoryById(5).getName());
        System.out.println(new NewsCategoryDaoImpl().getNewsCategoryById(6).getName());

    }
}
